//
//  LGTPersonVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/7.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import ZHRefresh

class LGTPersonVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource{
    var tableView:UITableView?
    var data:Array<Dictionary<String, Any>> = Array.init()
    var serverClick:ClickIndexBlock?
    var topClick:ClickIndexBlock?
    var userModel:UserModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
    }
    
    override func setUI() {
        
        self.view.backgroundColor = UIColor.white
        self.setBavBarStyle(navBarHiden: true, title: "我的", back: true)
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: 0.0, width: Double(KScreenW), height: Double(KScreenH) - TabBarH()), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self as UITableViewDelegate
        self.tableView?.dataSource = self as UITableViewDataSource
        self.tableView?.register(LGTRWZPersonTopCell.classForCoder(), forCellReuseIdentifier: "topCell")
        self.tableView?.register(LGTRWZPersonServerCell.classForCoder(), forCellReuseIdentifier: "serverCell")
        weak var weakSelf = self
        self.tableView?.header = ZHRefreshNormalHeader.headerWithRefreshing(block: {
            weakSelf?.getUserInfo()
        })
    }
    
    func setBlock(){
        weak var weakSelf = self
        self.reloadBlock = {()in
            weakSelf?.initData()
        }
        
        self.topClick = {
            (index:Int) in
            switch index {
                //用户信息
            case PersonTopClickType.UserInfoType.rawValue:
                let userInfoVC = LGTUserInfoVC()
                weakSelf?.navigationController?.pushViewController(userInfoVC, animated: true)
                break
                //发布任务
            case PersonTopClickType.ChangePublicer.rawValue:
                weakSelf?.changeUserType(user_type: 1)
                break
                //做任务
            case PersonTopClickType.ChangeMakeTask.rawValue:
                weakSelf?.changeUserType(user_type: 2)
                break
                //待处理
            case PersonTopClickType.OrderWaitDeal.rawValue:
                weakSelf?.orderViewShow(type: PersonTopClickType.OrderWaitDeal.rawValue)
                break
                //处理中
            case PersonTopClickType.OrderDeal.rawValue:
                weakSelf?.orderViewShow(type: PersonTopClickType.OrderDeal.rawValue)
                break
                //成功
            case PersonTopClickType.OrderSuccess.rawValue:
                weakSelf?.orderViewShow(type: PersonTopClickType.OrderSuccess.rawValue)
                break
                //失败
            case PersonTopClickType.OrderFail.rawValue:
                weakSelf?.orderViewShow(type: PersonTopClickType.OrderFail.rawValue)
                break
            case PersonTopClickType.UserMoney.rawValue:
                let walletVC = LGTWalletVC()
                weakSelf?.navigationController?.pushViewController(walletVC, animated: true)
                break
            default:
                break
            }
        }
        
        self.serverClick = {(index:Int) in
            switch index {
            //钱包
            case 0:
                let walletVC = LGTWalletVC()
                weakSelf?.navigationController?.pushViewController(walletVC, animated: true)
                break
                //消息中心
            case 1:
                let noteVC:LGTMessageNoteVC = LGTMessageNoteVC()
                weakSelf?.navigationController?.pushViewController(noteVC, animated: true)
                break;
                
            case 2:
                let feedVC:LGTAdviceFeedVC = LGTAdviceFeedVC()
                weakSelf?.navigationController?.pushViewController(feedVC, animated: true)
                break
                //设置
            case 3:
                let setVC = LGTUserSetVC()
                weakSelf?.navigationController?.pushViewController(setVC, animated: true)
                
                break
            default:
                break
            }
            
        }
    }
    
    func orderViewShow(type:Int){
        self.tabBarController?.selectedIndex = 2
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                    NotificationCenter.default.post(name: Order_ViewChange_Note, object: nil, userInfo: ["type":type])
        }
    }
    
    //切换角色
    func changeUserType(user_type:Int){
        let param:Dictionary<String, Any> = ["type": user_type]
        //weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: User_Chose_URL, param: param, showMessage: true, success: { (json) in
                //数据存储
            let userInfo:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            LGTUserUtil.share.updateUserInfo(data:  userInfo)
            //发布角色变化消息
            NotificationCenter.default.post(name: User_Role_Change_Note, object: nil)
        }) { (json) in
            
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let info:Dictionary<String, Any> = self.data[indexPath.row]
        let isTop:Bool = info["isTop"] as? Bool ?? false
        if isTop == true{
            let cell:LGTRWZPersonTopCell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath) as! LGTRWZPersonTopCell
            cell.model = info
            cell.clickBlock = self.topClick
            return cell
        }else{
            let cell:LGTRWZPersonServerCell = tableView.dequeueReusableCell(withIdentifier: "serverCell", for: indexPath) as! LGTRWZPersonServerCell
            cell.model = info
            cell.clickBlock = self.serverClick
            return cell
        }
    }
    
    func initData(){
        if self.userModel == nil{
            self.userModel = UserModel()
        }
        
        self.data = [
            ["isTop":true, "user":self.userModel!],
            ["myServer":true]
        ]
        self.tableView?.reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getUserInfo()
    }
    
    func getUserInfo(){
        
        //self.showLoading(loadingType: .TabbarLoadingType)
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: User_Info_URL, param: [:], success: { (json) in
            let data:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            let userModel:UserModel = try! lgtDecode(UserModel.self, param: (data))
            weakSelf?.userModel = userModel
            LGTUserUtil.share.updateUserInfo(data:data)
            weakSelf?.initData()
            weakSelf?.noView?.isHidden = true
            weakSelf?.tableView?.header?.endRefreshing()
           // weakSelf?.closeLoading()
        }) { (json) in
            //weakSelf?.showNoData(image: Net_NoData_Image, text: Net_Error_Text, subText: Net_Reload_Text, haveNav:false)
            //weakSelf?.closeLoading()
            weakSelf?.tableView?.header?.endRefreshing()
        }
    }
}
